package org.jeecg.modules.util;

import java.util.HashMap;
import java.util.Map;

public class CosineSimilarity {
    public static double cosineSimilarity(String text1, String text2) {
        Map<String, Integer> freqMap1 = getFrequencyMap(text1);
        Map<String, Integer> freqMap2 = getFrequencyMap(text2);

        double dotProduct = 0.0;
        double magnitude1 = 0.0;
        double magnitude2 = 0.0;

        for (Map.Entry<String, Integer> entry : freqMap1.entrySet()) {
            String key = entry.getKey();
            int freq1 = entry.getValue();
            dotProduct += freq1 * freqMap2.getOrDefault(key, 0);
            magnitude1 += Math.pow(freq1, 2);
        }

        for (int freq : freqMap2.values()) {
            magnitude2 += Math.pow(freq, 2);
        }

        if (magnitude1 == 0 || magnitude2 == 0) {
            return 0.0;
        }

        return dotProduct / (Math.sqrt(magnitude1) * Math.sqrt(magnitude2));
    }

    private static Map<String, Integer> getFrequencyMap(String text) {
        Map<String, Integer> freqMap = new HashMap<>();
        String[] words = text.split("\\s+");
        for (String word : words) {
            freqMap.put(word, freqMap.getOrDefault(word, 0) + 1);
        }
        return freqMap;
    }

    public static void main(String[] args) {
        String text1 = "我爱自然语言处理";
        String text2 = "自然语言处理很有趣";
        double similarity = cosineSimilarity(text1, text2);
        System.out.println("余弦相似度: " + similarity);
    }
}

